package ijij41.togetherTrain.participate;

import ijij41.network.NetworkRequester;
import ijij41.togetherTrain.*;
import ijij41.togetherTrain.common.RoomViewActivity;
//import ijij41.togetherTrain.participate.RoomListActivity.SeparatedListAdapter;
import ijij41.togetherTrain.personal.MyTicketListActivity;
import ijij41.togetherTrain.recruit.RoomCreateActivity;
import ijij41.togetherTrain.resource.MyTicketRoomListRow;
import ijij41.togetherTrain.resource.RoomListRow;
import ijij41.togetherTrain.resource.RoomListRow;

import java.util.*;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

public class RoomListActivity extends Activity implements Constants {

	private ArrayList<RoomListRow> listSearch;
	private ArrayList<RoomListRow> relatedListSearch;
	private TrainListAdapter trainListAdapter;
	private TrainListAdapter relatedTrainListAdapter;
	private String m_date;
	private String m_trainNum;
	private String m_startTime;
	private String m_startStation;
	private String m_endTime;
	private String m_endStation;
	private ListView listView;
	private SeparatedListAdapter adapter;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		// this.setContentView(R.layout.room_list);
		// setContentView(R.layout.room_list);
		this.setContentView(R.layout.room_list);

		initComponent();
	}

	@Override
	protected void onResume() {
		super.onResume();

		// this.runOnUiThread(new Runnable() {
		// public void run() {

		// }
		// });

		// setContentView(R.layout.room_list);

		// final Handler handler = new Handler();
		//
		// handler.post(new Runnable() {
		// public void run() {
		// // For remote TEST
		// ArrayList<RoomListRow> coll = NetworkRequester.getInstance()
		// .getRoomList(m_date, m_trainNum, m_startTime,
		// m_startStation, m_endTime, m_endStation);
		//

		// listSearch.clear();
		// listSearch.addAll(coll);
		//
		// trainListAdapter.notifyDataSetChanged();
		//
		// // list.refreshDrawableState();
		// // list.invalidate();
		// // listView.requestLayout();
		//
		// ViewGroup vg = (ViewGroup) findViewById(R.id.room_list);
		// vg.invalidate();
		// //vg.refreshDrawableState();
		//
		// // listView.removeAllViews();
		// // listView.refreshDrawableState();
		//
		// // ViewGroup vg = (ViewGroup) findViewById(R.layout.room_list);
		// // vg.invalidate();
		// //
		//
		// // trainListAdapter.getC
		// // relatedTrainListAdapter.notifyDataSetChanged();
		// }
		// });

//		Runnable updateUI = new Runnable() {
//			public void run() {
//
//				ArrayList<RoomListRow> coll = NetworkRequester.getInstance()
//						.getRoomList(m_date, m_trainNum, m_startTime,
//								m_startStation, m_endTime, m_endStation);
//

//				listSearch.clear();
//				listSearch.addAll(coll);
//
//				trainListAdapter.notifyDataSetChanged();
//				adapter.notifyDataSetChanged();
//
//				// listView.invalidate();
//
//			}
//		};
//		runOnUiThread(updateUI);
		

		ArrayList<RoomListRow> coll = NetworkRequester.getInstance()
				.getRoomList(m_date, m_trainNum, m_startTime, m_startStation,
						m_endTime, m_endStation);

		// TODO [Last Modify] 챗팅개발 필요 related 열차가 필요하다.
		// 챗팅을 꾸미는데 있어서, 기본적으로 특정 그룹에 들어 왔다고 가정 하고. 챗팅이 원할히 되도록 한후, 기존의 것이랑 (만들어 놓은것) 연결해본다.
		// 1. 방생성기능과 사용자 인증기능 필요  2. 멀티 유저 챗팅기능 필요. 2. user 정보 kgetfrom으로 가져오니 실제 사용자를 모르므로, 확인 가능한 솔루션 필요.
		listSearch.clear();
		listSearch.addAll(coll);

		//trainListAdapter.notifyDataSetChanged();
		adapter.notifyDataSetChanged();

	}

	private void initComponent() {

		listSearch = new ArrayList<RoomListRow>();
		relatedListSearch = new ArrayList<RoomListRow>();

		trainListAdapter = new TrainListAdapter(this, R.layout.search_row,
				listSearch);
		relatedTrainListAdapter = new TrainListAdapter(this,
				R.layout.search_row, relatedListSearch);

		// get parameters from before activity
		Intent intent = getIntent();

		m_date = intent.getStringExtra("date");
		m_trainNum = intent.getStringExtra("trainNum");
		m_startTime = intent.getStringExtra("startTime");
		m_startStation = intent.getStringExtra("startStation");
		m_endTime = intent.getStringExtra("endtTime");
		m_endStation = intent.getStringExtra("endStation");
		// ///////////////////////

		Log.v("TRAIN", "date : " + m_date);
		Log.v("TRAIN", "trainNum : " + m_trainNum);
		Log.v("TRAIN", "startTime : " + m_startTime);
		Log.v("TRAIN", "startStation : " + m_startStation);
		Log.v("TRAIN", "endtTime : " + m_endTime);
		Log.v("TRAIN", "endStation : " + m_endStation);

		// relatedListSearch.addAll(coll);
		// relatedListSearch.addAll(coll);


		// create our list and custom adapter
		adapter = new SeparatedListAdapter(this);
		adapter.addSection("조회 열차 정보", trainListAdapter);
		adapter.addSection("관련 열차 정보", relatedTrainListAdapter);
		listView = (ListView) findViewById(R.id.room_list);
		listView.setOnItemClickListener(mItemClickListener);
		listView.setAdapter(adapter);

		// event handler
		findViewById(R.id.btn_back_img).setOnClickListener(mClickListener);
		// findViewById(R.id.btn_create_room).setOnClickListener(mClickListener);

	}

	private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			RoomListRow myTicketRoomListRow = (RoomListRow) arg0.getAdapter()
					.getItem(position);

			Intent roomViewIntent = new Intent(RoomListActivity.this,
					RoomViewActivity.class);

			roomViewIntent.putExtra("room_idx", myTicketRoomListRow.getIdx());

			startActivity(roomViewIntent);

		}

	};

	private Button.OnClickListener mClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			case R.id.btn_back_img:
				finish();
				break;

			case R.id.btn_create_room:

				// Intent roomCreateIntent = new Intent(RoomListActivity.this,
				// RoomCreateActivity.class);
				//
				// /*trainListActivity.putExtra("time","10:00");
				// trainListActivity.putExtra("startStation","서울");
				// trainListActivity.putExtra("endStation","부산");
				// trainListActivity.putExtra("numPerson","1");*/
				//
				// // get parameters from before activity
				// Intent intent = getIntent();
				//
				// String date = intent.getStringExtra("date");
				// String trainNum = intent.getStringExtra("trainNum");
				// String startTime = intent.getStringExtra("startTime");
				// String startStation = intent.getStringExtra("startStation");
				// String endTime = intent.getStringExtra("endtTime");
				// String endStation = intent.getStringExtra("endStation");
				//
				//
				//
				//
				// roomCreateIntent.putExtra("function",FROM_RESERVATION);
				//
				// roomCreateIntent.putExtra("date",date);
				// roomCreateIntent.putExtra("trainNum",trainNum);
				// roomCreateIntent.putExtra("startTime",startTime);
				// roomCreateIntent.putExtra("startStation",startStation);
				// roomCreateIntent.putExtra("endtTime",endTime);
				// roomCreateIntent.putExtra("endStation",endStation);
				//
				//
				// startActivity(roomCreateIntent);
				//

				break;

			default:
				break;
			}

		}
	};

	public class TrainListAdapter extends ArrayAdapter<RoomListRow> {

		private ArrayList<RoomListRow> items;

		public TrainListAdapter(Context context, int textViewResourceId,
				ArrayList<RoomListRow> objects) {
			super(context, textViewResourceId, objects);

			items = objects;

		}

		public View getView(int position, View v, ViewGroup parent) {

			Log.v("TRAIN", "getView : " + position);
			// layout에다가 데이터를 담아서 리턴시켜야 하는데, layout을 어떻게 초기화 시키는가?
			// Inflater는 지정한 layout의 객체들을 모두 생성하고 생성된 객체간의 계층구조까지 완성해주는 놈
			LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.room_list_row, null);

			// 보여주어야할 항목이 몇번째 항목이냐에 따라 그에 맞는 데이터 추츨
			RoomListRow u = items.get(position);

			if (u != null) {
				TextView trainNumTv = (TextView) v.findViewById(R.id.train_num);
				TextView startStationTv = (TextView) v
						.findViewById(R.id.start_station);
				TextView startTimeTv = (TextView) v
						.findViewById(R.id.start_time);
				TextView endStationTv = (TextView) v
						.findViewById(R.id.end_station);
				TextView endTimeTv = (TextView) v.findViewById(R.id.end_time);

				TextView roomNumTv = (TextView) v
						.findViewById(R.id.room_num_value);

				TextView roomMasterTv = (TextView) v
						.findViewById(R.id.room_master_value);
				TextView roomMemberNumTv = (TextView) v
						.findViewById(R.id.room_member_num_value);

				trainNumTv.setText(u.getTrainNum());

				roomNumTv.setText(u.getRoom_num());
				roomMasterTv.setText(u.getMaster_id());
				roomMemberNumTv.setText(u.getReservationPersonNum() + "/"
						+ u.getMaxNumMember());

				startStationTv.setText(u.getStartStation());
				startTimeTv.setText(u.getStartTime());
				endStationTv.setText(u.getEndStation());
				endTimeTv.setText(u.getEndTime());

				/*
				 * if (tv1 != null) tv1.setText(u.getLabel()); if (tv2 != null)
				 * tv2.setText(u.getContent());
				 */
			}
			return v;
		}
	}

	private class SeparatedListAdapter extends BaseAdapter {

		public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
		public final ArrayAdapter<String> headers;
		public final static int TYPE_SECTION_HEADER = 0;

		public SeparatedListAdapter(Context context) {
			headers = new ArrayAdapter<String>(context, R.layout.list_header);
		}

		public void addSection(String section, Adapter adapter) {
			this.headers.add(section);
			this.sections.put(section, adapter);
		}

		public Object getItem(int position) {
			for (Object section : this.sections.keySet()) {
				Adapter adapter = sections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return section;
				if (position < size)
					return adapter.getItem(position - 1);

				// otherwise jump into next section
				position -= size;
			}
			return null;
		}

		public int getCount() {
			// total together all sections, plus one for each section header
			int total = 0;
			for (Adapter adapter : this.sections.values())
				total += adapter.getCount() + 1;
			return total;
		}

		public int getViewTypeCount() {
			// assume that headers count as one, then total all sections
			int total = 1;
			for (Adapter adapter : this.sections.values())
				total += adapter.getViewTypeCount();
			return total;
		}

		public int getItemViewType(int position) {
			int type = 1;
			for (Object section : this.sections.keySet()) {
				Adapter adapter = sections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return TYPE_SECTION_HEADER;
				if (position < size)
					return type + adapter.getItemViewType(position - 1);

				// otherwise jump into next section
				position -= size;
				type += adapter.getViewTypeCount();
			}
			return -1;
		}

		public boolean areAllItemsSelectable() {
			return false;
		}

		public boolean isEnabled(int position) {
			return (getItemViewType(position) != TYPE_SECTION_HEADER);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int sectionnum = 0;
			for (Object section : this.sections.keySet()) {
				Adapter adapter = sections.get(section);
				int size = adapter.getCount() + 1;

				// check if position inside this section
				if (position == 0)
					return headers.getView(sectionnum, convertView, parent);
				if (position < size)
					return adapter.getView(position - 1, convertView, parent);

				// otherwise jump into next section
				position -= size;
				sectionnum++;
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

	}

	// TODO [참고]
	// http://jsharkey.org/blog/2008/08/18/separating-lists-with-headers-in-android-09/

}
